package com.java2001.config;


import com.java2001.pojo.User;
import com.java2001.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userServiceImpl;


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("UserRealm ==> 授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        info.addRole(currentUser.getRole() == 1 ? "admin" : "test");

        return info;
    }


    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("UserRealm ==> 认证doGetAuthenticationInfo");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userServiceImpl.queryUserById(token.getUsername());
        //如果不为空，就检查密码，
        // 检查密码的过程是SimpleAuthenticationInfo做的
        if(user != null){
            //若密码不正确则返回IncorrectCredentialsException异常
            return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        }
        //若用户名不存在则返回UnknownAccountException异常
        return null;
    }
}
